<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页答题系统</title>
    <link th:href="@{/css/list_mb.css}" rel="stylesheet"/>
    <script th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
    <!-- 左侧分类 -->
    <div id="category-header">
	    <div id="category-nav">
	        <div class="category-item active" data-category="math">数学题</div>
	        <div class="category-item" data-category="history">历史题</div>
	    </div> 
    </div>
    
    <div id="content-wrapper">
        <div class="stats-bar">
            <div>已答：<span id="total-answered">0</span></div>
            <div>正确：<span id="correct-count">0</span></div>
            <div>正确率：<span id="accuracy">0</span>%</div>
        </div>
        <div id="questions-container"></div>
        <div class="load-more" onclick="handleScroll()">点击加载下一页</div>
    </div>
<script>
// 模拟分页数据
const mockData = {
    math: Array.from({length: 50}, (_, i) => ({
        type: i % 2 === 0 ? 'single' : 'multiple',
        question: `数学题 ${i + 1}`,
        options: { A: "选项A", B: "选项B", C: "选项C", D: "选项D" },
        answer: i % 2 === 0 ? 'B' : ['A', 'C'],
        explanation: `这是第 ${i + 1} 题的解析`
    })),
    history: Array.from({length: 30}, (_, i) => ({
        type: 'single',
        question: `历史题 ${i + 1}`,
        options: { A: "选项A", B: "选项B", C: "选项C" },
        answer: 'A',
        explanation: `历史题 ${i + 1} 解析`
    }))
};

let currentState = {
    category: 'math',
    page: 0,
    pageSize: 20,
	totalPage: 3,
    totalAnswered: 0,
    correctCount: 0,
    loading: false,
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
	updateRand();
	loadCategory();
    //loadQuestions();
    setupEventListeners();
});

function updateRand(){
	$.ajax({
	    url: "/updateRand",
	    data:{type: "1"},
	    async: false, // 设置为 false 以使请求同步
	    success: function(response) {
	        console.log("Success:", response);
	    },
	    error: function(xhr, status, error) {
	        console.log("Error:", error);
	    }
	});
}

async function loadCategory(){
	$.post('/getType', {favFlag:1}, (data)=>{
		const nav = $('#category-nav');
		nav.empty();
		nav.append('<div class="category-item " data-category="">ALL</div>');
		nav.append('<div class="category-item " data-category="A">XTK</div>');
		data.map( (item,index) => {
			if(index == 0){
				currentState.category = item.dlType;
			}
			nav.append('<div class="category-item '+(index==0?' active ': '')+' " data-category="'+item.dlType+'">'+item.dlType+'</div>')
		});
		loadQuestions();
	});
}

$('body').on('click', '.category-item', function(){
	 $('.category-item ').removeClass('active');
     $(this).addClass('active');
     currentState.category = $(this).attr('data-category');
     console.log(currentState.category);
     currentState.page = 0;
     $('#questions-container').html('');
     loadQuestions();
	 $('.load-more').css('display',  'block');
	 
	 currentState.totalAnswered = 0;
	 currentState.correctCount = 0;
	 $('#total-answered').text('0');
	 $('#correct-count').text('0');
	 $('#accuracy').text('0');
});

$('body').on('click', '.fav-btn', function(){
	var favFlag = 0;
	var tkId = $(this).attr('data-id');
	var fav = $(this).attr('data-fav');
	var obj = $(this);
	$.post('/update',{tkId : tkId, favFlag: fav == 1 ? 0 : 1 }, (data)=>{
		obj.attr('data-fav', fav == 1 ? 0 : 1);
		$(this).html(fav == 1 ? '未收藏' : '已收藏');
	});
	
});
$('body').on('click', '.stats-modal', function(){
	$(this).css('display','none');
})

function setupEventListeners() {
    // 分类切换
    document.querySelectorAll('.category-item').forEach(item => {
        item.addEventListener('click', () => {
            document.querySelector('.category-item.active').classList.remove('active');
            item.classList.add('active');
            currentState.category = item.dataset.category;
            currentState.page = 0;
            document.getElementById('questions-container').innerHTML = '';
            loadQuestions();
			document.querySelector('.load-more').style.display = 'block';
        });
    });

    // 滚动加载
    document.getElementById('questions-container').addEventListener('scroll', handleScroll);

    // 统计弹窗
    /* document.getElementById('toggle-stats').addEventListener('click', () => {
        const modal = document.querySelector('.stats-modal');
        modal.style.display = modal.style.display === 'block' ? 'none' : 'block';
    }); */
}

// 加载题目
async function loadQuestions() {
    if (currentState.loading) return;
    currentState.loading = true;

    // 模拟异步加载
    setTimeout(() => {
        /* const data = mockData[currentState.category];
        const start = (currentState.page - 1) * currentState.pageSize;
        const end = start + currentState.pageSize;
        const pageData = data.slice(start, end);

        renderQuestions(pageData);
        currentState.page++;
        currentState.loading = false; */
        
        var curPage = currentState.page + 1;
        $.post('/getAsk',{current:curPage, limit: currentState.pageSize, dlType: currentState.category, favFlag:1, rand:"1" }, (data)=>{
        	currentState.page = curPage,
        	currentState.totalPage = data.pages;
        	currentState.loading = false;
        	renderQuestions(data.records);
        })
        
    }, 500);
}

function renderQuestions(questions) {
    const container = document.getElementById('questions-container');
    
    questions.forEach((q, i) => {
        const questionEl = document.createElement('div');
        const startNo = (currentState.page - 1) * currentState.pageSize + i + 1;
        let expl =  '';
        if(q.explanation){
        	expl = encodeURIComponent(q.explanation);
        }
        questionEl.className = 'question-card';
        questionEl.innerHTML = `
            <h3>${startNo}、${q.question}</h3>
            <div class="options-container">
                ${Object.entries(q.options).map(([key, value]) => `
                    <label class="option-item">
                        <input id="${q.tkId}" type="${q.type === 'single' ? 'radio' : 'checkbox'}" 
                              name="q${i}" 
                              value="${key}">
                        ${key}. ${value}
                    </label>
                `).join('')}
            </div>
            <button class="answer-btn fav-btn" data-id="${q.tkId}" data-fav="${q.favFlag}" >${q.favFlag == 1 ? '已收藏': '未收藏'}</button>
            
            ${q.type === 'multiple' ? 
                `<button class="answer-btn" style="margin-left:5px" id="${q.tkId}" onclick="submitMultiple(this, '${q.answer}', '${expl}')">提交答案</button>` : ''}
            <div class="answer-info"></div>
        `;

        if (q.type === 'single') {
            questionEl.querySelectorAll('input').forEach(input => {
                input.addEventListener('change', (e) => 
                    checkSingle(e.target, q.answer, expl, questionEl));
            });
        }

        container.appendChild(questionEl);
    });
}

// 检查单选题
function checkSingle(input, answer, explanation, container) {
    const isCorrect = input.value === answer;
    updateStats(isCorrect);
    
    container.querySelectorAll('.option-item').forEach(item => {
        item.classList.remove('correct', 'incorrect');
        const radio = item.querySelector('input');
        if (radio.value === answer) item.classList.add('correct');
        if (radio.checked && !isCorrect) item.classList.add('incorrect');
    });
    if(!isCorrect){
    	updateError(input.id);
    }

    showFeedback(isCorrect, answer, explanation, container);
}

function updateError(tkId){
	$.post('/update',{tkId : tkId, errorFlag: 1}, (data)=>{
		console.log(data);
	});
}

function updateFav(btn, tkId, favFlag){
	$.post('/update',{tkId : tkId, favFlag: favFlag == 1 ? 0 : 1 }, (data)=>{
		console.log(data);
		btn.innerHTML = favFlag == 1 ? '未收藏' : '已收藏';
	});
}

// 提交多选题
function submitMultiple(button, answer, explanation) {
    const container = button.parentElement;
    const selected = Array.from(container.querySelectorAll('input:checked'))
                        .map(i => i.value);
    const correctAnswers = answer.split(',');
    
    const isCorrect = selected.length === correctAnswers.length &&
                     selected.every(v => correctAnswers.includes(v)) &&
                     correctAnswers.every(v => selected.includes(v));

    updateStats(isCorrect);
    if(!isCorrect){
    	updateError(button.id);
    }
    
    container.querySelectorAll('.option-item').forEach(item => {
        const value = item.querySelector('input').value;
        item.classList.remove('correct', 'incorrect');
        if (correctAnswers.includes(value)) item.classList.add('correct');
        if (selected.includes(value) && !correctAnswers.includes(value)) 
            item.classList.add('incorrect');
    });

    showFeedback(isCorrect, correctAnswers, explanation, container);
}

// 显示反馈信息
function showFeedback(isCorrect, answer, explanation, container) {
    const answerInfo = container.querySelector('.answer-info');
    const exp = decodeURIComponent(explanation);
    //if (!isCorrect) {
        answerInfo.innerHTML = `
            <p>正确答案：${Array.isArray(answer) ? answer.join(', ') : answer}</p>
            <p>解析：${exp}</p>
        `;
    //} else {
    //    answerInfo.innerHTML = '';
    //}
}

// 更新统计
function updateStats(isCorrect) {
    currentState.totalAnswered++;
    if (isCorrect) currentState.correctCount++;
    
    document.getElementById('total-answered').textContent = currentState.totalAnswered;
    document.getElementById('correct-count').textContent = currentState.correctCount;
    document.getElementById('accuracy').textContent = 
        ((currentState.correctCount / currentState.totalAnswered) * 100 || 0).toFixed(1);
}

// 滚动加载处理
function handleScroll() {
    //const container = document.getElementById('questions-container');
    //const { scrollTop, scrollHeight, clientHeight } = container;
    //alert(124);
    //if (scrollTop + clientHeight >= scrollHeight - 50) {
    	//alert(124);
		if(currentState.page > currentState.totalPage){
            document.querySelector('.load-more').style.display = 'none';
	    }else{
		   loadQuestions();
		}
    //}
}
</script>
</body>
</html>